<template>
  <div class="left">
    <el-form :model="inboundForm" ref='inboundRef' label-width="120px" :rules="inboundOrderRules">
      <div
        style="width: 100%; height: 32px; padding: 0 10px; margin-bottom: 20px; background-color: #ede9e9; font-size: 14px; line-height: 32px; color: #2a2e33; text-align: left;">
        入库数据：</div>
      <el-form-item class="left-input" label="采购方式" :required="true" prop="orderType">
        <el-select v-model="inboundForm.orderType" placeholder="请选择采购方式" @change="changeType()">
          <el-option label="采购入库" value="0" />
          <el-option label="借货入库" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item class="left-input" label="入库单号" :required="true">
        <el-input v-model="inboundOrderCode" disabled />
      </el-form-item>
      <el-form-item class="left-input" v-if="inboundType" label="供应商" style="width: 60%;" 
        prop="supplierId">
        <div style="width:100%;display: flex">
          <el-select v-model="supplierTypeModel" placeholder="请选择供应商类型" style="width: 60%;">
            <el-option v-for="item in supplierType" :key="item" :value="item" :label="item"></el-option>
          </el-select>
          <el-select v-model="inboundForm.supplierId" placeholder="搜索匹配/扫码" style="width: 60%;">
            <el-option v-for="item in supplierList.filter((item) => item.supplierType == supplierTypeModel)"
              :key="item.supplierName" :label="item.supplierName" :value="item.id" />
          </el-select>
          <el-button type="primary" v-if="supplierList.length == 0" @click="openAddSupplier()">新增供应商</el-button>
        
        
        </div>
        <!-- <el-button @click="dialogVisible1 = true" style="color:#1890ff;">添加</el-button> -->
      
      
      </el-form-item>
      


      <div  id="selectWarehouse">


        <el-form-item label="选择仓库" :required="true" style="width: 60%;">
            <el-cascader ref="articleOrgRef" v-model="inboundForm.desWarehouseId" :options="storageOptions"
              placeholder="打开选择仓位"
              :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true, children: 'storages', value: 'warehouseId', label: 'warehouseName', }"
              @change="cascaderHanlderChange" @expand-change="handleExpandChange" style="width: 60%;" />
          </el-form-item>

      </div>

      <div v-if="inboundType"
        style="width: 100%; height: 32px; padding: 0 10px; margin-bottom: 20px; background-color: #ede9e9; font-size: 14px; line-height: 32px; color: #2a2e33; text-align: left;">
        入库明细：</div>
      <el-form-item class="left-input" label="货品条码" prop="barcode">
        <el-input v-model="inboundForm.barcode" />
      </el-form-item>
      <el-form-item class="left-input" v-if="!inboundType" label="借入客户" style="width: 60%;" :required="true"
        prop="clientId">
        <el-select v-model="inboundForm.clientId" placeholder="搜索匹配/扫码" style="width: 60%;">
          <el-option v-for="item in clientList" :key="item.id" :label="item.clientName" :value="item.id" />
        </el-select>
        <!-- <el-button @click="dialogVisible1 = true" style="color:#1890ff;">添加</el-button> -->
      </el-form-item>
      <el-form-item class="left-input" v-if="!inboundType" label="有效期至" style="width: 60%;" 
        prop="validDate">
        <el-input v-model="inboundForm.validDate" @change="vailiInputDate" placeholder="请输入有效天数"></el-input>
        <!--<el-date-picker v-model="inboundForm.validDate" type="date" placeholder="选择有效期">
        </el-date-picker>-->
      </el-form-item>
      <!-- v-model="inboundForm.jadeTypeId" -->
      <el-form-item class="left-input" label="材质款式" style="width: 60%;">
        <el-cascader  :options="options" v-model="jadeCascaderVal" placeholder="打开选择品类" ref="jadeCascaderRef"
          :props="{ expandTrigger: 'hover', emitPath: false }" @change="handleChangejadeType" style="width: 60%;" />
      </el-form-item>
      <el-form-item class="left-input" label="货品数量" :required="true" prop="jadeQuantity">
        <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="imageUrlList.length" disabled="true"
          style="width: 200px;" />
        <el-select v-model="inboundForm.unit" prop="unit" >
          <el-option v-for="(item,index) in units" :key="index" :label="item.value" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="left-input" label="成本价" :required="true" prop="jadeCostPrice">
        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="inboundForm.jadeCostPrice"
          style="margin-bottom: 5px;" />
        <el-button @click="getCipher1()" style="color:#1890ff;">生成暗码</el-button>
        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="inboundForm.jadeCostCipher"
          style="width: 70%;margin-left:5px" disabled />
      </el-form-item>

      <el-form-item label="标签价" :required="true" prop="jadeTagPrice">
        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="inboundForm.jadeTagPrice"
          @input="($event) => onInputChange($event, 'tag')" style="width: 140px;" />
        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="rate"
          style="width: 40%; margin-left: 10px;margin-bottom: 5px;" @input="($event) => onInputChange($event, 'rate')">
          <template v-slot:append>
            倍率
          </template>
        </el-input>
        <span style="margin: 0 10px; font-size: 14px; color: #696c6f;margin-left: 30px;">数据类型：</span>
        <el-select v-model="operation" placeholder="" style="width: 150px;"
          @change="($event) => onInputChange($event, 'type')">
          <el-option label="向下取整" value="floor"></el-option>
          <el-option label="向上取整" value="ceil"></el-option>
          <el-option label="四舍五入" value="round"></el-option>
          <el-option label="保留小数" value="toFixed"></el-option>
        </el-select>
        <el-button @click="getCipher2()" style="color:#1890ff;">生成暗码</el-button>
        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="inboundForm.jadeTagPriceCipher"
          style="width: 70%;margin-left:5px" disabled />
      </el-form-item>
      <el-form-item class="left-input" label="市场价">
        <el-input oninput="value=value.replace(/[^\d.]/g,'')" v-model="inboundForm.jadeMarketPrice" />
      </el-form-item>
      <el-form-item class="left-input" label="备注">
        <el-input v-model="inboundForm.remark" />
      </el-form-item>
      <div v-if="inboundType"
        style="width: 100%; height: 32px; padding: 0 10px; margin-bottom: 20px; background-color: #ede9e9; font-size: 14px; line-height: 32px; color: #2a2e33; text-align: left;">
        操作：</div>
        <el-form-item class="left-input" label="是否数据缓存">
        <el-switch v-model="inboundForm.isstore" inline-prompt active-text="是" inactive-text="否" />
        <el-text tag="ins" style="padding-left: 20px;color:#1890ff;">缓存字段</el-text>
        <el-tooltip content="打开缓存后将保存上次入库的信息，条码自动加 1" placement="top">
          <el-icon>
            <QuestionFilled />
          </el-icon>
        </el-tooltip>
      </el-form-item>
      <el-form-item class="left-input" label="是否入库后打印">
        <el-switch v-model="inboundForm.isprint" inline-prompt active-text="是" inactive-text="否" />
        <el-text tag="ins" style="padding-left: 20px;color:#1890ff;">Rongta RP4</el-text>
      </el-form-item>
      <!-- <el-form-item class="left-input" label="是否入库后拍照">
        <el-switch v-model="isphoto" />
      </el-form-item> -->
      <el-radio-group v-model="inboundForm.codeRule" id="barcodeRule">
  <el-radio :label="0">相同条码</el-radio>
  <el-radio :label="1">递增条码</el-radio>
</el-radio-group>
      <!-- <el-form-item class="left-input" label="打印数量">
        <el-input v-model="remark" />
      </el-form-item> -->
    </el-form>

    <div class="left-end">
      <el-button type="primary" :loading="loading" @click.native.prevent="onSubmit">
        <span v-if="!loading">确认入库</span>
        <span v-else>入 库 中...</span>
      </el-button>
      <el-button @click="cleanForm">重置</el-button>
    </div>
  </div>

  <div class="right">
    <div class="right-photo">
      <!-- <div id='video-id' style="width: 100%;"></div> -->
      <video ref="videoElement" class="rigth-video" width="400" height="300" autoplay></video>
      <canvas ref="canvasElement" class="right-img"></canvas>
    </div>
    <div class="right-action">
      <el-upload action="http://8.134.106.197:9001/common/uploadImage" class="upload" :headers="{ Authorization: token }"
        :show-file-list="false" accept=".png,.jpg,.jpeg,.webp" style="display: inline-block;" :name="file"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-error="console.log(error)"
        :on-success="handleUpload" :before-upload=handleUploadBefore>
        <el-button style="color:#1890ff;">上传</el-button>
      </el-upload>
      <el-button @click="takePhoto" style="color:#1890ff;margin-left: 10px;">拍照</el-button>
      <el-button @click.native.prevent="triggerCamera" style="color:#1890ff;">{{ cameraActive ? '关闭摄像头' : '打开摄像头'
      }}</el-button>
    </div>
    <!-- <div class="right-action">
      <el-upload action="http://8.134.106.197:9001/common/uploadImage" class="upload" :headers="{ Authorization: token }"
        :show-file-list="false" accept=".png,.jpg,.jpeg,.webp" style="display: inline-block;" :name="file"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-error="console.log(error)"
        :on-success="handleUpload">
      </el-upload>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
        <el-input>3</el-input>
      </el-dialog>
      <el-button @click="takePhoto" style="color:#1890ff;margin-left: 10px;">拍照</el-button>
      <el-button @click.native.prevent="triggerCamera" style="color:#1890ff;">{{ cameraActive ? '关闭摄像头' : '打开摄像头'
      }}</el-button>
    </div> -->
    <el-col class="imageBox">
      <div v-for="(photo, index) in imageUrlList" :key="index" class="imgList"
        style="display: flex; flex-direction: column;">
        <el-image :src="'http://8.134.106.197:9001/profile' + photo.imageUrl" alt="Photo" fit="contain"
          style="height: 120px; width: auto;"
          :preview-teleported="true" :lazy="true" :preview-src-list="imgPreview"
          @click="previewSrcList(photo.imageUrl)"></el-image>
        <!-- <el-input-number class="img-num" v-model="photo.num" :min="1" size="small" controls-position="right" /> -->
        <span>成本价： {{ photo.jadeCost }}</span>
        <span>标签价： {{ photo.jadeTagPrice }}</span>
        <el-icon class="img-del" @click="handleDelteImg(photo.imageId)">
          <Close />
        </el-icon>
      </div>
    </el-col>
    <el-col class="right-tips">已上传图片数{{ imageUrlList.length }}</el-col>

    <div>
      <el-dialog v-model="dialogVisiblePrint">
        <div id="printArea" class="right-print">
          <vue-barcode :value="inboundForm.barcode" format="CODE128" displayValue="true" width="1" height="35"
            font-size="15"></vue-barcode>
          <el-button v-print="printTest">打印</el-button>
        </div>
      </el-dialog>
    </div>
    <el-button @click="openPrint">打印</el-button>
  </div>

  <div class="dialog-list">
    <el-dialog v-model="dialogVisible1" title="添加供应商" width="30%" :before-close="handleClose" :show-close="false">
      <div>
        <el-form :model="supplierForm" label-width="120px" :rules="supplierRules" ref="supplierRef">
          <el-form-item label="供应商编码" prop="supplierCode" :required="true">
            <el-input v-model="supplierForm.supplierCode" disabled />
          </el-form-item>

          <el-form-item label="供货商性质" prop="supplierType" :required="true">
            <el-select v-model="supplierForm.supplierType" placeholder="请选择供货商性质" @change="changeType()">
              <el-option label="采购员工" value="采购员工" />
              <el-option label="外部供应商" value="外部供应商" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工姓名" prop="buyerName" :required="true">
            <el-input v-model="supplierForm.buyerName" />
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工身份证号" :required="true">
            <el-input v-model="supplierForm.buyerIdcard" />
          </el-form-item>
          <el-form-item v-if="supplierType" label="采购员工手机号" prop="buyerPhone" :required="true">
            <el-input v-model="supplierForm.buyerPhone" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName" :required="true">
            <el-input v-model="supplierForm.supplierName" />
          </el-form-item>
          <el-form-item v-if="!supplierType" label="供应商对接人姓名" prop="buyerName" :required="true">
            <el-input v-model="supplierForm.buyerName" />
          </el-form-item>
          <el-form-item v-if="!supplierType" label="供应商对接人手机号" prop="buyerPhone" :required="true">
            <el-input v-model="supplierForm.buyerPhone" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="supplierForm.address" />
          </el-form-item>
          <el-form-item label="结款模式" :required="true">
            <el-select v-model="supplierForm.settlementWay" placeholder="请选择结款模式">
              <el-option label="银行转账" value="银行转账" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="收款人姓名" :required="true">
            <el-input v-model="supplierForm.payeeName" />
          </el-form-item>
          <el-form-item label="收款人账户" :required="true">
            <el-input oninput="value=value.replace(/[^\d]/g,'')" v-model="supplierForm.payeeAccount" />
          </el-form-item>
          <el-form-item label="收款人开户行" :required="true">
            <el-input v-model="supplierForm.payeeBank" />
          </el-form-item>
          <el-form-item label="结算方式" :required="true">
            <el-select v-model="supplierForm.settlementType" placeholder="请选择结算方式">
              <el-option label="成本价百分比结算" value="成本价百分比结算" />
              <el-option label="标签价百分比结算" value="标签价百分比结算" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="supplierForm.remark" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取消</el-button>
          <el-button type="primary" @click="handleAddSupplierSubmit">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { onBeforeMount, onMounted, reactive, ref, defineComponent, watch } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { Plus, QuestionFilled, Close } from '@element-plus/icons-vue';
import moment from 'moment';
import { getSupplierList, getSupplierCode ,addSupplier } from "@/api/user/user"
import { getToken } from '@/utils/auth'
import { getOrderCode, inbounding, getJadeCode, addJade, getJadeCrop, getJadeFeature, getJadeType, getCipherText } from '@/api/inbound/inbound'
import { getWarehouseListV2, getStorageList, getStorageCascader, getStorageCode } from '@/api/setting/setting';
import { getClientList } from "@/api/user/user"
import VueBarcode from 'vue3-barcode';
import axios from 'axios'
export default defineComponent({
  name: 'loginAccount',
  components: {
    Plus,
    QuestionFilled,
    Close,
    VueBarcode,
  },
  setup() {
    const dialogVisiblePrint = ref(false)
    const dialogVisibleImg = ref(false)
    const dialogVisible1 = ref(false)//添加供应商

    const loading = ref(false)
    const inboundRef = ref()
    const barcodeRule = ref(0)
    const inboundType = ref(true)
    const videoElement = ref(null)
    const canvasElement = ref(null)
    const cameraActive = ref(false)
    const videoStream = ref(null)
    const dialogImageUrl = ref('')

    const rate = ref(2.0)
    const magnification = ref(2.0)//倍率控制
    const operation = ref('floor')
    const token = ref('')


    const units = ref([
      {key:'件',value:"件"},
      {key:'个',value:"个"},
      {key:'条',value:"条"},
      {key:'对',value:"对"},
      {key:'只',value:"只"},
      {key:'克',value:"克"},
      {key:'套',value:"套"},
      {key:'盒',value:"盒"},
      {key:'盘',value:"盘"},
      {key:'袋',value:"袋"},
      {key:'箱',value:"箱"},
      {key:'串',value:"串"},
      {key:'块',value:"块"},
      {key:'包',value:"包"},
      {key:'片',value:"片"},
      {key:'饼',value:"饼"},
      {key:'公斤',value:"公斤"},
      {key:'千克',value:"千克"},
      {key:'提',value:"提"},
      {key:'罐',value:"罐"}
    ])
    const inboundOrderCode = ref(1)
    const imageUrlList = ref([])
    const imgPreview = ref([])

    //表单验证规则对象inboundOrderRules
    const inboundOrderRules = reactive({
      barcode:[{ required: true, message: '货品条码不能为空', trigger:'blur'},
               { validator: validateBarcode, required: true, trigger:'change'}],

      orderType: [{ required: true, message: '采购方式不能为空', trigger: 'change' },],
      supplierId: [{ required: true, message: '供应商不能为空', trigger: 'change' },],
      clientId: [{ required: true, message: '客户不能为空', trigger: 'change' },],
      desStorageId: [{ required: true, message: '仓位不能为空', trigger: 'change' },],
      desWarehouseId: [{ required: true, message: '仓库不能为空', trigger: 'change' },],
      jadeQuantity: [{ required: true, message: '货品数量不能为空', trigger: 'blur' },],
      unit: [{ required: true, message: '货品单位不能为空', trigger: 'blur' },],
      jadeCostPrice: [{ required: true, message: '成本价不能为空', trigger: 'blur' },],
      jadeTagPrice: [{ required: true, message: '标签价不能为空', trigger: 'blur' },],
      validDate: [{ type: 'date', required: true, message: '请选择到期时间', trigger: 'blur' },
                  { validator: validateDate, trigger: 'blur' },],
    });

    //日期选择的验证规则
    
function validateDate(rule, value, callback) {
  const currentMoment = moment();
  if (value && moment(value).isAfter(currentMoment)) {
    callback();
  } else {
    callback(new Error('时间不能早于当前时间'));
  }
}
     //计算时间
     const vailiInputDate = function (e) {
    // 计算 inboundForm.validDate + 当前时间
    // 将当前时间转换为日期对象
    const currentDate = new Date();
    if (inboundForm.validDate) {
        // 将 validDate 转换为毫秒数，并加到当前日期上
        const newDate = new Date(currentDate.getTime() + inboundForm.validDate * 24 * 60 * 60 * 1000);
        inboundForm.validDate = `${newDate.getFullYear()}-${String(newDate.getMonth() + 1).padStart(2, '0')}-${String(newDate.getDate()).padStart(2, '0')}`;
        console.log('计算后的 validDate:', inboundForm.validDate);
    } else {
        console.error('validDate 为空，可能存在问题');
    }
};
    // 货品条形码的验证规则
    function validateBarcode() {
  let lastAlertTime = 0; // 上次提示的时间戳

  // 返回验证函数
  return function(rule, val, callback) {
    // 判断输入的字符是否包含英文字母
    const containsLetter = /[a-zA-Z]/.test(val);

    // 获取当前时间戳
    const currentTime = new Date().getTime();

    // 如果输入的字符包含英文字母，并且距离上次提示超过 10s
    if (containsLetter && (currentTime - lastAlertTime > 10000)) {
      // 触发提示
      ElMessage({
        title: '警告',
        message: '输入内容包含英文字母！',
        type: 'warning'
      });
      // 更新上次提示的时间戳
      lastAlertTime = currentTime;
    }

    // 始终调用 callback 表示验证通过
    callback();
  };
}

    //入库表单数据
    const inboundForm = reactive({
      orderType: '',
      orderCode: '',
      supplierId: '',
      desWarehouseId: 0,
      desStorageId: 0,
      inboundDetailDTOList: [],
      validDate: '',
      barcode: 123,//条形码
      jadeWeight: '',
      jadeTagPrice: '',
      jadeTagPriceCipher: '',
      jadeCostPrice: '',
      jadeCostCipher: '',
      jadeQuantity: 0,
      unit:'件',
      orderDate: "",
      validDate: "",
      deptId: "1",
      remark: '',
      jadeTypeId: 1,
      jades: [],
      codeRule: 0,//1-递增 0-相同
      //控制开关
      isstore: false,
      isprint: false,
      isphoto: false,

    })
    const jadeForm = reactive({
      jadeCode: '',
      orderCode: 1,
      jadeTypeId: 1,
      jadeName: "佛",
      jadeBarcode: "",
      storageId: 1,
      warehouseId: 1,
      jadeCost: 0,
      jadeTagPrice: 0,
      jadeWeight: 1,
      imageId: 0,
      deptId: 1,
    })
    const supplierForm = reactive({ //供应商表单数据
      name: '',
      payeeName: '',
      payeeAccount: '',
      phone: '',
      address: '',
      settlement: '',
      settleratio: '',
      alertDay: '',
      note: '',
      authority1: false,
      authority2: false,
    });
    const supplierList = ref([
    ])
    const supplierType = ref([])
    const supplierTypeModel = ref()
    const clientList = ref([
    ])
    const warehouseList = ref([
    ])
    const storageList = ref([
    ])
    const imgsList = ref([//图像列表

    ])
    const options = ref([])//品类列表
    const treeList = ref([])
    const storageOptions = ref([])//仓库级联列表

    const articleOrgRef = ref(null)

    const inboundDetailDTOObj = reactive({
      imageId: '', // 图片ID
      jadeBarcode: '', // 翡翠条形码
      jadeTypeId: '', // 翡翠类型ID
      jadeQuantity: 1, // 一个入库单数据
      unit:'件',
      jadeCost: '',// 成本价
      jadeCostCipher: '', // 成本价暗骂
      jadeTagPrice: '', // 标签价
      jadeTagPriceCipher: '', // 标签价暗码
      jadeMarketPrice: '', // 市场价
      remark: '' // 备注
    })
      const arr = ref(null)

    //
    const cascaderHanlderChange = () => {
    const pathArr = articleOrgRef.value.getCheckedNodes()[0].pathNodes;
    const warehouseId = pathArr[0].data.warehouseId;
    const cangweiId = pathArr[1].data.id;
    inboundForm.desStorageId = cangweiId;
    inboundForm.desWarehouseId = warehouseId;
    console.log('inboundForm after cascader change:', inboundForm);
    if (cangweiId === 0) {
        console.error('仓位 ID 为 0，可能存在问题');
    }
};
    onBeforeMount(() => {//获取数据
      token.value = getToken()
      getCascader()
      getJadeType().then((res) => {
        res.data.forEach((item) => {
          if (item.children) {
            let temp = []
            item.children.forEach((item_c) => {
              temp.push({ value: item_c.id, label: item_c.jadeTypeName })
            })
            options.value.push({ value: item.id, label: item.jadeTypeName, children: temp }); // 将新的元素对象添加到结果数组中
          }
          else {
            options.value.push({ value: item.id, label: item.jadeTypeName }); // 将新的元素对象添加到结果数组中
          }
        })
      })
      getSupplierList().then((res) => {
        supplierList.value = res.rows
        supplierType.value = Array.from(new Set(res.rows.map(item => item.supplierType)))
        console.log(supplierType.value)
      })
      getWarehouseListV2().then((res) => {
        warehouseList.value = res.rows
      })

      getClientList().then((res) => {
        clientList.value = res.rows
      })
      getOrderCode().then((res) => {
        inboundOrderCode.value = res//获取入库单单号
        inboundForm.barcode = parseInt(res.substring(12, 22))
        inboundForm.orderCode = res
      })
      getStorageList().then((res) => {
        storageList.value = res.rows
        // inboundForm.desStorageId = res.rows[0].storageName
      })
    })
    const clearForm = () => {
      supplierForm.supplierName = ''
      supplierForm.remark = ''
      supplierForm.address = ''
      supplierForm.buyerPhone = ''
      supplierForm.buyerName = ''
      supplierForm.payeeAccount = ''
      supplierForm.payeeName = ''
      supplierForm.payeeBank = ''
      supplierForm.buyerIdcard = ''
    }
    const supplierRules = reactive({
      supplierName: [{ required: true, message: '请输入内容', trigger: 'blur' },
      { min: 2, max: 8, message: '名称长度在 2 到 8长度之间', trigger: 'blur' }],
      supplierType: [{ required: true, message: '该选项不能为空', trigger: 'blur' }],
      buyerName: [{ required: true, message: '请输入内容', trigger: 'blur' },
      { min: 2, max: 8, message: '名称长度 在 2 到 8长度之间', trigger: 'blur' }],
      buyerPhone: [{ required: true, message: '请输入内容', trigger: 'blur' }, {
        type: 'number',
        message: '手机号格式不正确',
        trigger: 'blur',
        transform(value) {
          var phonereg = 11 && /^((13|14|15|16|17|18|19)[0-9]{1}\d{8})$/
          if (!phonereg.test(value)) {
            return false
          } else {
            return Number(value)
          }
        }
      }]
    });
    const supplierRef = ref();
    const handleAddSupplierSubmit = () => {
      supplierRef.value.validate((valid) => {
        if (valid) {
          addSupplier(supplierForm).then((res) => {
            res.code == 200 ? ElMessage.success('添加成功') : ElMessage.error(res.msg)
            clearForm()
            dialogVisible1.value = false
          })
        } else {
          return false;
        }
      });
    }
    //打开新增供应商
    const openAddSupplier = () => {
      dialogVisible1.value = true
      getSupplierCode().then((res) => {
        supplierForm.supplierCode = res
      })
    }
    onMounted(() => {    //周期函数  生成条形码
    })
    const dateTurn = (dateTime) => {//时间格式转换
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      return formattedDate
    }

    const getParentStorage = (val) => {
      // console.log(val)
      // for (const item of treeList.value) {//第一层
      //   if (item.id == val) {
      //     inboundForm.desStorageId = item.value
      //     inboundForm.desWarehouseId = item.id
      //   }
      //   if (item.childrenStorages.length != 0) {//递归往下
      //     if (findLabelByValue(item.childrenStorages, val)) {
      //       inboundForm.desWarehouseId = findLabelByValue(item.childrenStorages, val)
      //       console.log(inboundForm.desStorageId, inboundForm.desWarehouseId)
      //       return
      //     }
      //   }
      // }
    }
    function findLabelByValue(tree, targetValue) {
      for (const node of tree) {
        if (node.id == targetValue) {
          inboundForm.desStorageId = node.id
          return node.parentWarehouse
        }
        if (Array.isArray(node.children)) {
          const value = findLabelByValue(node.children, targetValue);
          if (value) {
            return value
          }
        }
      }
      return null
    }

    const getCascader = () => {
      getStorageCascader().then((res) => {
        treeList.value = res

        // res && Array.isArray(res) && res.forEach((warehouse) => {
        //   const warehouseNode = {
        //     value: warehouse.id,
        //     label: warehouse.warehouseName,
        //     parentStorage: warehouse.parentStorage,
        //     parentWarehouse: warehouse.parentWarehouse,
        //     children: []
        //   }
        //   warehouse.childrenStorages.forEach(storage => {
        //     const storageNode = {
        //       value: storage.id,
        //       label: storage.storageName,
        //       parentStorage: storage.parentStorage,
        //       parentWarehouse: storage.parentWarehouse,
        //       children: []
        //     }
        //     if (storage.children.length != 0) {
        //       console.log(parseNestedData(storage.children))
        //       storageNode.children = (parseNestedData(storage.children))
        //     }
        //     warehouseNode.children.push(storageNode)
        //   })
        //   tree.children.push(warehouseNode);
        // })
        const tmpTree = res
        tmpTree.forEach(item => {

        })
        storageOptions.value = modifyData(res);
        filterDisableItem(storageOptions.value)
      })
    }

    function modifyData(data) {
      return data.map(warehouse => ({
        ...warehouse,
        storages: modifyStorages(warehouse.storages, warehouse.warehouseCode, warehouse.warehouseName),
      }));
    }

    function modifyStorages(storages, warehouseCode, warehouseName) {
      return storages.map(storage => ({
        ...storage,
        warehouseCode: storage.storageCode,
        warehouseName: storage.storageName,
      }));
    }

    // 添加 diabled 过滤属性
    function filterDisableItem(arr) {
      arr.forEach(item => {
        item.disabled = true
        if (item.warehouseStatus == '2' || item.warehouseStatus == '3') {
          item.storages.forEach(item => {
            item.disabled = true
          })
        }
      })
    }

    function parseNestedData(data) {
      if (!Array.isArray(data)) {
        return [];
      }
      return data.map(item => {
        const parsedItem = {
          value: item.id,
          label: item.storageName,
          parentStorage: item.parentStorage,
          children: []
        }

        if (item.children.length != 0) {
          parsedItem.children = parseNestedData(item.children);
        }

        return parsedItem;
      });
    }

    const openPrint = () => {
      dialogVisiblePrint.value = true
    }

    const takePhoto = () => { //调用摄像头后拍照
      const video = videoElement.value
      const canvas = canvasElement.value
      if (cameraActive.value) {
        if (video) try {
          // 将视频画面绘制到画布上
          const context = canvas.getContext('2d')
          // canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height)
          const devicePixelRatio = window.devicePixelRatio || 1
          // 设置 Canvas 元素的实际大小
          canvas.width = 2000 * devicePixelRatio   // 宽度为 400 像素
          canvas.height = 1500 * devicePixelRatio  // 高度为 300 像素
          // 缩放 Canvas 以适应屏幕
          context.scale(devicePixelRatio, devicePixelRatio);
          // 绘制一些内容
          context.fillStyle = 'red'
          context.drawImage(video, 0, 0, canvas.width, canvas.height)
          // 将画布内容转换为图片 URL
          // 将canvas内容转换为Blob对象
          canvas.toBlob(blob => {
            // 使用Blob对象创建URL
            const formData = new FormData()
            formData.append("file", blob, "image.png")
            // 使用 Axios 发送 POST 请求
            axios.post("http://8.134.106.197:9001/common/uploadImage", formData, {
              headers: {
                "Content-Type": "multipart/form-data",
                "Authorization": token.value,
              },
            }).then((res) => {
              getJadeCrop({ image_path: res.data.url.slice(34) }).then((res_crop) => {//分割图片
                if (res_crop.code !== 200) {
                    ElMessage.error(res_crop.message)
                }

                for (var key in res_crop.result) {
                  imageUrlList.value.push({ imageId: key, imageUrl: res_crop.result[key], num: 1 })
                }
                inboundForm.jadeQuantity = imageUrlList.value.length
                imageUrlList.value.forEach((item) => {
                  getJadeCode().then((code) => {
                    item.code = code
                  })
                })
                console.log('分割结果' + res_crop)
              })
            })
              .catch((error) => {
                // 处理上传失败的错误
                console.error(error)
              })
          });

        }
          catch (error) {
            ElMessage.error('摄像头拍照失败')
          }
      }
      else {
        ElMessage.error('请先打开摄像头')
      }

    };
    const triggerCamera = async () => {

      if (cameraActive.value) {
        videoStream.value.getTracks().forEach(track => track.stop())//关闭摄像头代码
        videoElement.value.srcObject = null
        cameraActive.value = false
      } else {
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
          navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
              videoStream.value = stream
              videoElement.value.srcObject = stream
              cameraActive.value = true
            })
            .catch(error => {
              console.log(error)
              ElMessage.error('获取摄像头失败')
            });
        }
        else {
          ElMessage.error('获取摄像头失败，请检查是否已连接摄像头')
        }

      }
    };
    const handleUpload = (res) => {
      getJadeCrop({ image_path: res.url.slice(34) }).then((res_crop) => {
        if (res_crop.code !== 200) {
            ElMessage.error(res_crop.message)
        }
        for (var key in res_crop.result) {
          imageUrlList.value.push({
            imageId: key,
            jadeBarcode: inboundForm.barcode,
            jadeTypeId: inboundForm.jadeTypeId,
            jadeQuantity: 1,
            unit:'件',
            jadeCost: inboundForm.jadeCostPrice,
            jadeCostCipher: inboundForm.jadeCostCipher,
            jadeTagPrice: inboundForm.jadeTagPrice,
            jadeTagPriceCipher: inboundForm.jadeTagPriceCipher,
            jadeMarketPrice: inboundForm.jadeMarketPrice,
            remark: inboundForm.remark,
            imageUrl: res_crop.result[key],
            num: 1,
          })
        }
        inboundForm.jadeQuantity = imageUrlList.value.length
        // imageUrlList.value.forEach((item) => {
        //   getJadeCode().then((code) => {
        //     item.code = code
        //   })
        // })
      })
    }
    //打印
    const printTest = reactive({
      id: 'printArea', // 绑定打印区域的ID
      popTitle: ' ',
      standard: 'html5', // 默认打印文档类型，为html5（支持html5,loose,strict）
      previewBeforeOpenCallback() { console.log('预览') },
      endCallback: () => { // 打印后的回调函数
      }
    })
//删除图片
const handleDelteImg = (id) => {
  let indexToDelete = -1;
  imageUrlList.value.forEach((item, index) => {
    if (item.imageId === id) {
      indexToDelete = index;
    }
  });
  if (indexToDelete!== -1) {
    imageUrlList.value.splice(indexToDelete, 1);
  }
};

    const handlePictureCardPreview = (uploadFile) => {  //图片预览
      dialogImageUrl.value = uploadFile.url
      dialogVisibleImg.value = true
    }

    const cleanForm = () => { //重置表单
      console.log('清空表单')
      inboundRef.value.resetFields()
      ElMessage.success('清空成功')
    }
    const changeType = (value) => { //更换入库来源
      inboundForm.orderType == 1 ? inboundType.value = false : inboundType.value = true
    }
    const previewSrcList = (imgUrl) => {//预览图片
      imgPreview.value = []
      imgPreview.value.push('http://8.134.106.197:9001/profile' + imgUrl)
    }
    const handleExpandChange = (val) => {
      inboundForm.desWarehouseId = val[0]
    }
    const getCipher1 = () => {//生成成本价暗码
      if (inboundForm.jadeCostPrice) {
        getCipherText({ price: inboundForm.jadeCostPrice }).then(res => {
          if (res.code == 200) {
            inboundForm.jadeCostCipher = res.msg
          } else {
            ElMessage.error('生成暗码出现错误')
          }

        })
      } else {
        ElMessage.info('请先输入价格')
      }

    }
    const getCipher2 = () => {//生成标签价暗码
      if (inboundForm.jadeTagPrice) {
        getCipherText({ price: inboundForm.jadeTagPrice }).then(res => {
          if (res.code == 200) {
            inboundForm.jadeTagPriceCipher = res.msg
          } else {
            ElMessage.error('生成暗码出现错误')
          }
        })
      } else {
        ElMessage.info('请先输入价格')
      }

    }

//提交入库单
const onSubmit = () => {

   // 检查是否上传了图片
   if (imageUrlList.value.length === 0) {
        ElMessage.error('请先上传图片');
        return;
    }
    let errorMessage = '';
    if (!inboundForm.barcode) {
        errorMessage += '货品条码不能为空；';
    }
    if (!inboundForm.orderType) {
        errorMessage += '采购方式不能为空；';
    }
    if (!inboundForm.supplierId && inboundForm.orderType!== '1') {
        errorMessage += '供应商不能为空；';
    }
    if (!inboundForm.desWarehouseId) {
        errorMessage += '仓库不能为空；';
    }
    if (!inboundForm.desStorageId) {
        errorMessage += '仓位不能为空；';
    }
    if (!inboundForm.jadeQuantity) {
        errorMessage += '货品数量不能为空；';
    }
    if (!inboundForm.unit) {
        errorMessage += '货品单位不能为空；';
    }
    if (!inboundForm.jadeCostPrice) {
        errorMessage += '成本价不能为空；';
    }
    if (!inboundForm.jadeTagPrice) {
        errorMessage += '标签价不能为空；';
    }
    if (inboundForm.validDate && moment(inboundForm.validDate).isBefore(moment())) {
        errorMessage += '时间不能早于当前时间；';
    }
    if (errorMessage) {
        ElMessage.error(errorMessage);
        return;
    }
    // 检查是否上传了图片
    if (imageUrlList.value.length === 0) {
        ElMessage.error('请先上传图片');
        return;
    }
    ElMessageBox.confirm(
        '是否确认入库?',
        '提示',
        {
            confirmButtonText: '是',
            cancelButtonText: '取消',
            type: '提示',
        }
    ).then(() => {
        // 入库单数据赋值新建货品单
        if (inboundForm.orderType === '0') {
            inboundForm.validDate = '';
        } else {
            inboundForm.validDate = dateTurn(inboundForm.validDate);
        }
        loading.value = true;
        imageUrlList.value && Array.isArray(imageUrlList.value) && imageUrlList.value.forEach(item => {
            inboundForm.inboundDetailDTOList.push(item);
        });
        // 等后续接口业务逻辑改进再动
        // jadeForm.storageId = inboundForm.desStorageId;
        // jadeForm.warehouseId = inboundForm.desWarehouseId;
        // jadeForm.orderCode = inboundOrderCode;
        // jadeForm.orderType = inboundForm.orderType;
        // jadeForm.supplierId = inboundForm.supplierId;
        // jadeForm.jadeBarcode = inboundForm.barcode;
        // jadeForm.jadeCost = inboundForm.jadeCostPrice;
        // jadeForm.jadeTagPrice = inboundForm.jadeTagPrice;
        // jadeForm.jadeTypeId = inboundForm.jadeTypeId;
        // imageUrlList.value.forEach((item) => {
        //     let jadeTemp = {
        //         jadeCode: '',
        //         orderCode: inboundOrderCode,
        //         jadeTypeId: inboundForm.jadeTypeId,
        //         jadeName: "翡翠",
        //         storageId: inboundForm.desStorageId,
        //         warehouseId: inboundForm.desWarehouseId,
        //         jadeCost: inboundForm.jadeCostPrice,
        //         jadeBarcode: inboundForm.barcode,
        //         orderType: inboundForm.orderType,
        //         jadeTagPrice: inboundForm.jadeTagPrice,
        //         jadeWeight: 1,
        //         supplierId: inboundForm.supplierId,
        //         jadeQuantity: '',
        //         imageId: 0,
        //         deptId: 1,
        //     };
        //     jadeTemp.imageId = item.imageId;
        //     jadeTemp.jadeCode = item.code;
        //     jadeTemp.jadeQuantity = item.num;
        //     inboundForm.jades.push(jadeTemp);
        //     addJade(jadeForm);
        // });
        getJadeFeature({ data: imageUrlList.value });
        // 添加仓库id
        const paramsObj = {...inboundForm, StorageId: inboundForm.desStorageId, warehouseId: inboundForm.desWarehouseId };
        delete paramsObj.desStorageId;
        delete paramsObj.desWarehouseId;
        inbounding(inboundForm).then((res) => {
            if (res.code === 500) {
                let errorMessage = '入库失败';
                // 检查各个字段是否有问题并添加具体提示
                if (!inboundForm.barcode) {
                    errorMessage += '货品条码不能为空；';
                }
                if (!inboundForm.orderType) {
                    errorMessage += '采购方式不能为空；';
                }
                if (!inboundForm.supplierId && inboundForm.orderType!== '1') {
                    errorMessage += '供应商不能为空；';
                }
                if (!inboundForm.desWarehouseId) {
                    errorMessage += '仓库不能为空；';
                }
                if (!inboundForm.desStorageId) {
                    errorMessage += '仓位不能为空；';
                }
                if (!inboundForm.jadeQuantity) {
                    errorMessage += '货品数量不能为空；';
                }
                if (!inboundForm.unit) {
                    errorMessage += '货品单位不能为空；';
                }
                if (!inboundForm.jadeCostPrice) {
                    errorMessage += '成本价不能为空；';
                }
                if (!inboundForm.jadeTagPrice) {
                    errorMessage += '标签价不能为空；';
                }
                if (inboundForm.validDate && moment(inboundForm.validDate).isBefore(moment())) {
                    errorMessage += '时间不能早于当前时间；';
                }
                ElMessage.error(errorMessage);
            } else {
                ElMessage.success('入库成功');
                imageUrlList.value = [];
                loading.value = false;
                if (!inboundForm.isstore) {
                    inboundRef.value.resetFields();
                    getOrderCode().then((res) => {
                        inboundOrderCode.value = res; // 获取入库单单号
                        inboundForm.barcode = parseInt(res.substring(12, 22));
                        inboundForm.orderCode = res;
                    });
                } else {
                    getOrderCode().then((res) => {
                        inboundOrderCode.value = res; // 获取入库单单号
                        inboundForm.barcode = parseInt(res.substring(12, 22));
                        inboundForm.orderCode = res;
                    });
                }
            }
        });
    }).catch(() => {
        ElMessage.info('已取消');
    });
};
//  const onSubmit = () => {//提交入库单
//   console.log('orderType:', inboundForm.orderType);
//     console.log('supplierId:', inboundForm.supplierId);
//     console.log('desWarehouseId:', inboundForm.desWarehouseId);
//     console.log('desStorageId:', inboundForm.desStorageId);
//     console.log('jadeQuantity:', inboundForm.jadeQuantity);
//     console.log('unit:', inboundForm.unit);
//     console.log('jadeCostPrice:', inboundForm.jadeCostPrice);
//     console.log('jadeTagPrice:', inboundForm.jadeTagPrice);
    
//     //...
//       if (imageUrlList.value.length == 0) {
//         ElMessage.error('请先上传图片')
//         return
//       }
//       inboundRef.value.validate().then(() => {
//         ElMessageBox.confirm(
//           '是否确认入库?',
//           'Warning',
//           {
//             confirmButtonText: '是',
//             cancelButtonText: '取消',
//             type: 'warning',
//           }
//         ).then(() => {
//           // 验证通过
//           //入库单数据赋值新建货品单
//           if (inboundForm.orderType == '0') {
//             inboundForm.validDate = ''
//           } else {
//             inboundForm.validDate = dateTurn(inboundForm.validDate)
//           }
//           loading.value = true
//           imageUrlList.value && Array.isArray(imageUrlList.value) && imageUrlList.value.forEach(item => {
//             inboundForm.inboundDetailDTOList.push(item)
//           })
// //           //等后续接口业务逻辑改进再动
// //            jadeForm.storageId = inboundForm.desStorageId
// //           jadeForm.warehouseId = inboundForm.desWarehouseId
// //            jadeForm.orderCode = inboundOrderCode
// //          jadeForm.orderType = inboundForm.orderType
// //            jadeForm.supplierId = inboundForm.supplierId
// //            jadeForm.jadeBarcode = inboundForm.barcode
// //            jadeForm.jadeCost = inboundForm.jadeCostPrice
// //            jadeForm.jadeTagPrice = inboundForm.jadeTagPrice
// //            jadeForm.jadeTypeId = inboundForm.jadeTypeId
// //           imageUrlList.value.forEach((item) => {
// //            let jadeTemp = {
// //                jadeCode: '',
// //                orderCode: inboundOrderCode,
// //               jadeTypeId: inboundForm.jadeTypeId,
// //               jadeName: "翡翠",
// //                storageId: inboundForm.desStorageId,
// //               warehouseId: inboundForm.desWarehouseId,
// //                jadeCost: inboundForm.jadeCostPrice,
// //               jadeBarcode: inboundForm.barcode,
// //               orderType: inboundForm.orderType,
// //                jadeTagPrice: inboundForm.jadeTagPrice,
// //                jadeWeight: 1,
// //                supplierId: inboundForm.supplierId,
// //               jadeQuantity: '',
// //              imageId: 0,
// //               deptId: 1,
// //             }
// //              jadeTemp.imageId = item.imageId
// //             jadeTemp.jadeCode = item.code
// //             jadeTemp.jadeQuantity = item.num
// //             inboundForm.jades.push(jadeTemp)
// //            addJade(jadeForm)
// //            })
//           getJadeFeature({ data: imageUrlList.value })
//           //添加仓库id
//           const paramsObj = {...inboundForm, StorageId: inboundForm.desStorageId, warehouseId: inboundForm.desWarehouseId }
//           delete  paramsObj.desStorageId
//           delete  paramsObj.desWarehouseId
//           inbounding(inboundForm).then((res) => {
//             if (res.code == 500) {
//               ElMessage.error('入库失败')
//             } else {
//               ElMessage.success('入库成功')
//               imageUrlList.value = []
//               loading.value = false
//               if (!inboundForm.isstore) {
//                 inboundRef.value.resetFields()
//                 getOrderCode().then((res) => {
//                   inboundOrderCode.value = res//获取入库单单号
//                   inboundForm.barcode = parseInt(res.substring(12, 22))
//                   inboundForm.orderCode = res
//                 })
//               } else {
//                 getOrderCode().then((res) => {
//                   inboundOrderCode.value = res//获取入库单单号
//                   inboundForm.barcode = parseInt(res.substring(12, 22))
//                   inboundForm.orderCode = res
//                 })
//               }
//             }
//           })
//         }).catch(() => {
//           ElMessage.info('已取消')
//         })
//       }).catch((err) => {
//         //验证失败
//         ElMessage.error('请正确填写信息');
//         loading.value = false
//       })
//     }


    const onInputChange = function (e, type) {
      // 触发标签 ==》 重新计算比率forRate
      if (type == 'tag') {
        rate.value = calculateNumByType(operation.value, inboundForm.jadeCostPrice, e, rate.value, 'forRate');
      }
      // 触发比率 ==》 重新计算标签价forTag
      else if (type == 'rate') {
        inboundForm.jadeTagPrice = calculateNumByType(operation.value, inboundForm.jadeCostPrice, inboundForm.jadeTagPrice, e, 'forTag')
      }
      // 触发数据类型 ==》 重新计算标签价forType
      else if (type == 'type') {
        // rate.value = calculateNumByType( e, inboundForm.jadeCostPrice,inboundForm.jadeTagPrice, rate.value, 'forType' )
        inboundForm.jadeTagPrice = calculateNumByType(e, inboundForm.jadeCostPrice, inboundForm.jadeTagPrice, rate.value, 'forTag')
      }
    }

    /**
     * 根据数据类型计算数值：floor、ceil、round、toFixed
     * 输入：type(数据约数类型) cost(成本) tag(标签价) rate(比率) opType(计算类型：计算比率或者标签价)
     * 输出： rate 或者 jadeTagPrice
     */
    const calculateNumByType = function (type, cost, tag, rate, opType) {
      cost = Number(cost)
      rate = Number(rate)
      tag = Number(tag)
      if (opType == 'forTag') {
        /* 根据成本价和比率算 标签价 */
        // return (rate * cost).toFixed(2)
        switch (true) {
          case type == 'floor':
            return Math.floor(cost * rate)
          case type == 'ceil':
            return Math.ceil(cost * rate)
          case type == 'round':
            return Math.round(cost * rate)
          case type == 'toFixed':
            const num = cost * rate;
            return Number(num.toFixed(2))
          default:
            return 0
        }
      } else if (opType == 'forRate') {
        /* 根据成本价和标签价算 比率 */
        const num = tag / cost;
        return Number(num.toFixed(2))
        // switch (true) {
        //   case type == 'floor':
        //     return Math.floor(tag / cost)
        //   case type == 'ceil':
        //     return Math.ceil(tag / cost)
        //   case type == 'round':
        //     return Math.round(tag / cost)
        //   case type == 'toFixed':
        //     const num = tag / cost;
        //     return Number(num.toFixed(2))
        //   default:
        //     return 0
        // }
      } else if (opType == 'forType') {
        /* 根据成本价和标签价算 比率(数据类型改变的情况) */
        switch (true) {
          case type == 'floor':
            return Math.floor(cost * rate)
          case type == 'ceil':
            return Math.ceil(cost * rate)
          case type == 'round':
            return Math.round(cost * rate)
          case type == 'toFixed':
            const num = cost * rate;
            return Number(num.toFixed(2))
          default:
            return 0
        }
      }
    }
    function isNumberOrDecimal(str) {
      // 使用正则表达式检查
      const regex = /^-?\d*\.?\d+$/;
      return regex.test(str);
    }
    // 文件上传之前钩子
    const handleUploadBefore = function (file) {
      const test = isNumberOrDecimal(inboundForm.jadeCostPrice) && isNumberOrDecimal(inboundForm.jadeTagPrice)
      // console.log('dfjhgjk', inboundForm.jadeCostPrice , inboundForm.jadeTagPrice);
      if (!test) {
        ElMessage.warning('请输入标签价和成本价')
        return false
      }
    }

    // 货品品类Cascader的val
    const  jadeCascaderVal = ref(null)

    // jadeCascaderRef
    const jadeCascaderRef = ref(null)
    // 处理货品类型
    const handleChangejadeType = function (CascaderValue) {
      const pathArr = jadeCascaderRef.value.getCheckedNodes()[0].pathNodes
      const jadeNameId = pathArr[0].data.value
      // const jadeTypeName = ( pathArr[1] && pathArr[1].data ) ? pathArr[1].data.label : null
      const jadeTypeId = ( pathArr[1] && pathArr[1].data ) ? pathArr[1].data.value : null
      // const jadeTypeName = ( pathArr[1] && pathArr[1].data ) ? pathArr[1].data.label : null
      const idStr = jadeTypeId ? `${jadeNameId}-${jadeTypeId}` : `${jadeNameId}`
      inboundForm.jadeTypeId = idStr
    }

    // 监听成本价
    watch(() => inboundForm.jadeCostPrice, (newValue) => {//成本价控制标签价
      if (operation.value == 'floor') {
        inboundForm.jadeTagPrice = Math.floor(newValue * rate.value);
      } else if (operation.value == 'ceil') {
        inboundForm.jadeTagPrice = Math.ceil(newValue * rate.value);
      } else if (operation.value == 'round') {
        inboundForm.jadeTagPrice = Math.round(newValue * rate.value);
      } else if (operation.value == 'toFixed') {
        inboundForm.jadeTagPrice = parseFloat((newValue * rate.value).toFixed(1));
      }
    });
    // 监听标签价
    watch(() => inboundForm.jadeTagPrice, (newVal, oldVal) => {
    })
    // 收起选择框
    watch(() => inboundForm.desWarehouseId, (newVal, oldVal) => {

      if (articleOrgRef) {
        articleOrgRef.value.togglePopperVisible()
      }
    })
    return {

      inboundForm,onSubmit, supplierForm, jadeForm, inboundRef, inboundOrderRules, token, printTest,jadeCascaderVal,
      inboundOrderCode, barcodeRule, imgPreview, storageOptions, treeList, getParentStorage,jadeCascaderRef,
      dialogVisible1, cameraActive, videoStream, dialogVisibleImg, dialogImageUrl, dialogVisiblePrint,
      operation, rate, magnification, articleOrgRef, handleUploadBefore,
      videoElement, canvasElement, imageUrlList,arr,units,openAddSupplier,handleAddSupplierSubmit,vailiInputDate,
      options, imgsList, supplierList, clientList, warehouseList, storageList, inboundType,supplierType, supplierTypeModel,
      getCipher1, getCipher2, inboundDetailDTOObj,validateBarcode,supplierRef, parseNestedData,
      cleanForm, handleUpload, previewSrcList, handleDelteImg, openPrint, handleExpandChange, onInputChange,
      onSubmit, triggerCamera, takePhoto, handlePictureCardPreview, changeType, cascaderHanlderChange,handleChangejadeType
    };
  }
})
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@media print {

  .right-print {
    display: block;
    position: fixed;
    top: 40px;
    right: 45px;
    width: 80px;
    height: 60px;
  }

  vue-barcode {
    transform: scale(1);
    transform-origin: top left;
    width: 80px;
    height: 60px;
  }

  @page {
    size: auto;
    margin: 0mm;
    padding: 0mm;
    resolution: 800dpi;
  }
}



.left {
  float: left;
  width: 48%;
  // height: 800px;
  background-color: #fff;
  padding: 20px;

  .left-input {
    float: auto;
    margin-bottom: 13px;

    .el-form-item__label {
      font-size: x-small;
    }

 .el-input__wrapper {
      height: 25px;
    }
  }

  .left-end {
    margin-left: 20%;
  }
}

.right {
  float: right;
  width: 45%;
  // height: 800px;
  background-color: #fff;
  padding: 20px;

  .right-photo {
    width: 100%;
    border: solid 1px;
  }

  .right-tips {
    line-height: 40px;
    width: 100%;
    text-align: center;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }

  .rigth-video {
    flex: auto;
    width: 400px;
    height: 300px;
  }

  .right-img {
    flex: auto;
    // width: 400px;
    // height: 500px;
    position: absolute;
    top: -9999px;
    opacity: 0;
  }

  .right-action {
    width: 100%;
    height: 40px;
    margin: 10px;

    .el-upload {
      display: inline-block;
    }
  }

  .imageBox {
    min-height: 100px;
    height: 200px;
    border: solid 1px rgb(210, 210, 210);
    padding: 5px;
    display: flex;
    flex-wrap: wrap;
    flex-grow: 1; // 允许区域增长以适应内容
    overflow-y: auto; // 当内容超出时显示滚动条

    /* 图片之间的间距 */
    .imgList {
      height: 100%;
      padding-right: 10px;
      padding-bottom: 25px;
      /* 可根据需要调整每个图片元素的宽度 */
      margin-right: 10px;
      /* 图片之间的间距 */
     margin-bottom: 10px;
      /* 每行图片的底部间距 */
      position: relative;

      span {
        font-size: 14px;
        color: #2a2e33;
      }
    }

    .img-num {
      position: absolute;
      bottom: 1px;
      left: 50%;
      transform: translateX(-50%);
      width: 70px;
    }

    .img-del {
      position: absolute;
      top: 1px;
      right: 1px;
      height: 10px;
      width: 10px;
    }
  }
}</style>
